from django.http import JsonResponse
from django.views.generic import RedirectView, CreateView
from django.views.generic.edit import BaseFormView, FormView

from markdownx.views import ImageUploadView
from .forms import MarkdownxTestForm
from .models import MyModel


class InitView(RedirectView):

    pattern_name = 'user:login'


class MyImageUploadView(ImageUploadView):

    def form_valid(self, form):
        response = BaseFormView.form_valid(self, form)

        if self.request.is_ajax():
            image_path = form.save(commit=True)
            image_code = '![]({})'.format(image_path)
            return JsonResponse({'image_code': image_code})

        return response


class TestMarkdownxView(FormView):
    template_name = 'test/mdx.html'
    form_class = MarkdownxTestForm


class TestMarkdownxCreateView(CreateView):
    model = MyModel
    template_name = 'test/create.html'
    fields = ['myfield']

    def get_form(self, form_class=None):
        if form_class is None:
            form_class = self.get_form_class()
        return form_class(**self.get_form_kwargs())
